package 多线程案例;
//实现定时器


import java.util.PriorityQueue;

import static java.lang.System.currentTimeMillis;

//任务类
class MyTimeTask implements Comparable<MyTimeTask> {
    private long time;
    private Runnable runnable;
    public MyTimeTask(Runnable runnable ,int delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimeTask o) {
        return (int) (this.time-o.time);
    }

    public void run() {
        runnable.run();
    }
}

class MyTimer{
    //负责扫描队列
    Thread t = null;
    //采用优先级队列方式实现
    PriorityQueue<MyTimeTask> queue = new PriorityQueue<>();

    Object lock = new Object();
    //提供添加任务方法
    public void schedule(Runnable runnable,int delay){
        synchronized (lock){
            MyTimeTask task = new MyTimeTask(runnable,delay);
            queue.offer(task);
            lock.notify();
        }
    }
    //核心操作——控制时间，让他一运行就可以具有这个功能，放在构造器中

    //不要忘记线程安全问题
    public MyTimer(){
        t = new Thread(()->{
            //一直扫描

                while (true) {
                    try {
                        synchronized (lock) {
                        //判断是否为空，为空，无法扫描
                        while (queue.isEmpty()) {//使用while，被唤醒后再次比较
//                        continue;//一直退出，然后在进来，容易导致线程饥饿问题
                            lock.wait();
                        }
                        //判断时间到了吗
                        MyTimeTask task = queue.peek();
                        long nowTime = System.currentTimeMillis();
                        //如果时间到了，那么就从队列中取出，并开始运行
                        if (nowTime >= task.getTime()) {
                            queue.poll();
                            task.run();
                        } else {
                            lock.wait(task.getTime()-nowTime);
                        }
                    }
                } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
        });
        t.start();
    }
}

public class Demo_5 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("111");
            }
        },3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("222");
            }
        },2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("333");
            }
        },1000);
        System.out.println("开始运行");
    }
}
